import lxml
import requests
from bs4 import BeautifulSoup

# 获取双色球中奖号码信息
from tools import WriteArray
from tools import ReadConfigs


def GetData(number_of_element):
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) '
                      'Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE '
    }
    url = 'https://chart.cp.360.cn/kaijiang/ssq?lotId=220051&spanType=3&span=2003001_{}'.format(
        number_of_element)  # 爬取期数
    # print(url)
    my_response = requests.get(url, headers=headers, timeout=300)
    text = my_response.text
    soup = BeautifulSoup(text, 'lxml')

    tbody = soup.find_all('tbody', id="data-tab")[0]
    trs = tbody.find_all('tr')
    red = []  # 红球
    blue = []  # 蓝球
    red_list = []
    blue_list = []
    for tr in trs:
        tds = tr.find_all('td')[:4]
        blue.append(list(tds[3].stripped_strings)[0])  # 获取蓝球号码
        red_ball = ''
        for index, td in enumerate(tds):
            if index == 2:  # 红球
                for i in list(td.stripped_strings):
                    red_ball = red_ball + ' ' + i
                    red.append(int(i))
    total_num = int(len(red) / 6)
    for i in range(total_num):
        red_list.append(red[0 + 6 * i: 6 * (i + 1)])
    red_list.reverse()

    for i in blue:
        tmp = int(i)
        blue_list.append([tmp])
    blue_list.reverse()
    return red_list, blue_list


def UpdateData():
    configs = ReadConfigs()
    red_file_path = configs["RED_FILE_PATH"]
    blue_file_path = configs["BLUE_FILE_PATH"]
    periods_num = configs["PERIODS_NUMS"]

    red_list, blue_list = GetData(periods_num)
    WriteArray(red_list, red_file_path)
    WriteArray(blue_list, blue_file_path)
